import { Room, Client } from '@colyseus/core';
import { MapRoomState } from './schema/MapRoomState';
import { Player } from './schema/Player';  // 统一的房间状态管理

export class BaseRoom extends Room<MapRoomState> {
    maxClients = 10;  // 默认最大玩家数

    onCreate(options: any) {
        console.log(`🌍 ${this.roomId} 房间已创建`);
        this.setState(new MapRoomState());

        // 处理玩家加入房间
        this.onMessage('join', (client, message) => {
            console.log(`🎮 ${client.sessionId} 进入房间 ${this.roomId}`);
        });

        // 处理玩家切换地图
        this.onMessage('leave', (client, message) => {
            console.log(`🚶 ${client.sessionId} 离开房间 ${this.roomId}`);
            this.onLeave(client, false);  // 先移除，再让客户端加入新地图
        });

        // 处理玩家彻底退出游戏
        this.onMessage('exit', (client, message) => {
            console.log(`❌ ${client.sessionId} 退出游戏`);
            client.leave();
        });
    }

    onJoin(client: Client, options: any) {
        console.log('[onJoin options]',options)
        this.state.playerCount++;
        const newPlayer = new Player(client.sessionId, `玩家_${this.state.playerCount}`, 0, 0, 100, 'idle');
        this.state.players.set(client.sessionId, newPlayer);
        console.log(`✅ ${client.sessionId} 加入 ${this.roomId}`);
    }

    async onLeave(client: Client, consented: boolean) {
        console.log(`${client.sessionId} 断开连接 (consented=${consented})`);

        if (consented) {
            this.state.players.delete(client.sessionId);
        } else {
            // 允许玩家在 20 秒内重新连接
            try {
                await this.allowReconnection(client, 20);
                console.log(`${client.sessionId} 重新连接成功`);
            } catch {
                console.log(`${client.sessionId} 重新连接失败，彻底移除`);
                this.state.players.delete(client.sessionId);
            }
        }
    }

    onDispose() {
        console.log(`🗑️ ${this.roomId} 释放资源`);
    }
}
